#!/bin/bash

set -e

root=$(cd $(dirname ${0})/..; pwd)
node_modules=${root}/node_modules
src=${root}/src
third_party=${root}/third_party
tools=${root}/tools

identifier=caffe

bold() {
    echo "$(tty -s && tput bold)$1$(tty -s && tput sgr0)" 
}

git_sync() {
    mkdir -p "${third_party}"
    if [ -d "${third_party}/${1}" ]; then
        git -C "${third_party}/${1}" fetch --quiet -p
        git -C "${third_party}/${1}" reset --quiet --hard origin/master
    else
        git -C "${third_party}" clone --quiet --recursive ${2}
    fi
    git -C "${third_party}" submodule update --quiet --init
}

clean() {
    bold "caffe clean"
    rm -rf ${third_party}/caffe
}

sync() {
    bold "caffe sync"
    git_sync caffe https://github.com/BVLC/caffe.git
}

schema() {
    bold "caffe schema"
    sed 's/required float min = 1;/optional float min = 1;/g;s/required float max = 2;/optional float max = 2;/g' <${third_party}/${identifier}/src/caffe/proto/caffe.proto >${tools}/caffe.proto
    ${node_modules}/protobufjs/bin/pbjs -t static-module -w closure --no-encode --no-delimited --no-comments --no-convert --no-verify --no-create --keep-case --decode-text -r caffe -o ${src}/caffe-proto.js ${tools}/caffe.proto
    rm ${tools}/caffe.proto
    node ${tools}/update_pbjs.js array ${src}/caffe-proto.js data float 1
}

while [ "$#" != 0 ]; do
    command="$1" && shift
    case "${command}" in
        "clean") clean;;
        "sync") sync;;
        "schema") schema;;
    esac
done
